package com.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.model.User;
import com.service.UserService;
import com.service.UserServiceImpl;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    UserService userService;
    User user;
	
    public UserLoginServlet() throws SQLException {
        super();
        this.userService = new UserServiceImpl();
        this.user = new User();
        
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user.setUsername(username);
		user.setPassword(password);
		if(userService.userLogin(user)){
			HttpSession session = request.getSession();
			if(session.isNew()){
				request.setAttribute("welMsg", "欢迎新人，");
			}else{
				request.setAttribute("welMsg", "欢迎回来，");
			}
			session.setAttribute("user", user);
			request.getRequestDispatcher("index").forward(request, response);
			return;
		}
		request.setAttribute("msg", "用户名或密码错误");
		request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
		return;
	}

}
